import { Button, Table, Popover, Modal, notification, message } from 'antd';
import { SyncOutlined, ExclamationCircleOutlined } from '@ant-design/icons';
import router from 'umi/router';
import { useRequest, useBoolean } from '@umijs/hooks';
import AuthComponent from '@/components/Authorized/AuthComponent';
import React, { useState, useEffect, Fragment } from 'react';
import VerifyStep from '../VerifyStep/index';
import styles from './style.less';
import { intervalTime } from '@/utils/utils'; //格式化时间

import { closeCompensation, getOrderAuditRecord, getOrderSceneList } from '../../service';

const { confirm } = Modal;
const ListOfClaims = props => {
	const { compensationD, compensationL, flightNumDate, queryCompensation } = props;
	// 设置确认发放按钮的禁用 和 启用
	const { state: disBtn, setTrue, setFalse } = useBoolean(true);
	// 设置注销按钮的禁用 和 启用
	const { state: logoutBtn, setTrue: setLogoutTrue, setFalse: setLogoutFalse } = useBoolean(true);

	// 线下发放
	const { run } = useRequest((params) => closeCompensation(params), {
		manual: true,
		onSuccess: () => {
			queryCompensation(flightNumDate);
			notification.success({
				message: '成功',
				duration: 3,
				description: '操作完成'
			})
			setTrue();
		}
	});

	// 注销的方法
	const { run: runLogoutFun } = useRequest((params) => closeCompensation(params), {
		manual: true,
		onSuccess: () => {
			queryCompensation(flightNumDate);
			notification.success({
				message: '成功',
				duration: 3,
				description: '操作完成'
			})
			setTrue();
			setLogoutTrue();
		}
	});

	// 获取审核信息
	const { run: shInfo, data: sData = [] } = useRequest(params => getOrderAuditRecord(params),
		{
			manual: true,
			onSuccess: () => {
				handleVerify(true);
			}
		}
	)
	useEffect(() => {
		setTrue();
		setLogoutTrue();
		handleKeys([]);
		handleRows([])
		// eslint-disable-next-line react-hooks/exhaustive-deps
	}, [compensationD])

	const [verifystep, handleVerify] = useState(false);

	// 截取航段
	const filterContent = v => {
		let arr = v.split(',')
		if (arr.length === 1) {
			return (
				<div className={styles.popoverBox}>
					<p>
						<span>{v}</span>
					</p>
				</div>
			)
		}
		return (
			<div className={styles.popoverBox}>
				{
					arr.map((vl, index) => {
						return (
							<p key={index}>
								<span>{vl}</span>
							</p>
						)
					})
				}
			</div>
		)
	}

	// 补偿单列表
	const columns = [
		{
			title: '操作',
			dataIndex: 'option',
			width: 70,
			// hideInTable: !(AuthComponent.getAuth('compensation.index.auditPro')),
			render: (_, record) => [
				// <AuthComponent authCode="compensation.index.auditPro">
				<span onClick={() => {
					shInfo({
						orderId: record.orderId
					})
				}} style={{ cursor: "pointer" }}>
					<SyncOutlined />
				</span>
				//  </AuthComponent>
			],
		},
		{
			title: '状态',
			dataIndex: 'status',
			width: 100,
			render: v => (
				<>
					{/* <span style={{ display: v === '1' ? 'block' : 'none' }}>审核中</span>
					<span style={{ display: v === '2' ? 'block' : 'none' }}>通过</span>
					<span style={{ display: v === '3' ? 'block' : 'none' }}>不通过</span>
					<span style={{ display: v === '4' ? 'block' : 'none' }}>驳回</span>
					<span style={{ display: v === '6' ? 'block' : 'none' }}>已发放</span>
					<span style={{ display: v === '5' ? 'block' : 'none' }}>注销</span> */}
          <span style={{ display: v === '0' ? 'block' : 'none' }}>草稿</span>
					<span style={{ display: v === '1' ? 'block' : 'none' }}>审核中</span>
					<span style={{ display: v === '2' ? 'block' : 'none' }}>通过</span>
					<span style={{ display: v === '3' ? 'block' : 'none' }}>生效</span>
					<span style={{ display: v === '4' ? 'block' : 'none' }}>已关闭</span>
					<span style={{ display: v === '5' ? 'block' : 'none' }}>未通过</span>
					<span style={{ display: v === '6' ? 'block' : 'none' }}>驳回</span>
					<span style={{ display: v === '7' ? 'block' : 'none' }}>待审核</span>
					<span style={{ display: v === '8' ? 'block' : 'none' }}>已逾期</span>
					<span style={{ display: v === '9' ? 'block' : 'none' }}>注销</span>
					<span style={{ display: v === '10' ? 'block' : 'none' }}>已发放</span>
				</>
			)
		},
		{
			title: '补偿单号',
			dataIndex: 'orderId',
			width: 200
		},
		{
			title: '事故单号',
			dataIndex: 'accidentId',
			width: 200
		},
		{
			title: '补偿航段',
			dataIndex: 'choiceSegment',
			width: 150,
			render: (text, record) => (
				<Popover placement="bottom" content={filterContent(text)} title="" trigger="hover">
					<span className={styles.ellipsis}>{text}</span>
				</Popover>
			)
		},
		{
			title: '补偿数量',
			dataIndex: 'pkgCount',
			width: 120
		},
		{
			title: '补偿成本',
			dataIndex: 'pkgPrice',
			width: 120
		},
		{
			title: '申请人',
			dataIndex: 'paxName',
			width: 120
		},
		{
			title: '申请时间',
			dataIndex: 'createTime',
			width: 180
		},
		{
			title: '发放人',
			dataIndex: 'grantUser',
			width: 120
		},
		{
			title: '发放时间',
			dataIndex: 'grantTime',
			width: 180
		},
		{
			title: '注销人',
			dataIndex: 'cancelUser',
			width: 120
		},
		{
			title: '注销时间',
			dataIndex: 'cancelTime',
			width: 120
		},

	];

	// 记录多选是的的Id
	const [selectKeys, handleKeys] = useState([]);
	const [selectRows, handleRows] = useState([]);

	// 确认发放逻辑
	const confirmation = () => {
		// if (selectRows[0].createId === localStorage.getItem('userId')) {
			confirm({
				centered: true,
				title: '提示',
				icon: <ExclamationCircleOutlined />,
				content: (
					<div style={{ fontSize: "16px",color: "#ff5a5a" }}>请先确认箱包赔偿尺寸、成本等补偿信息无误，如核实无误，您可点击【继续】发放箱包。</div>
				),
				onOk() {
					run({
						orderId: selectKeys[0],
						status: '10' // 9注销 10箱包发放
					})
				},
				onCancel() {
				},
			});
		// } else {
		// 	message.error('非补偿单创建人，无补偿金额发放权限')
		// }
	};
	// 注销逻辑
	const logoutBtnFun = () => {
		confirm({
			centered: true,
			title: (
				<div style={{ color: "#000", fontSize: "18px", fontWeight: "bold" }}>提示</div>
			),
			icon: <ExclamationCircleOutlined />,
			content: (
				<div style={{ fontSize: "16px" }}><span style={{ color: "#ff5a5a" }}>注销后，该补偿单将被作废并将不计入报表统计，请确认是否【继续】？</span></div>
			),
			onOk() {
				runLogoutFun({
					orderId: selectKeys[0],
					status: '9' // 9注销 10箱包发放
				})
			}
		});
	}

	// 表格多选事件
	const onSelectChange = (selectedRowKeys, selectedRows) => {
		selectedRowKeys.length ? setFalse() : setTrue();
		// 注销（类型为异常行李---补偿单状态为通过或生效）
		if (selectedRowKeys.length === 1 &&
			selectedRows[0].payType === '1' &&
			(selectedRows[0].status === '2' || selectedRows[0].status === '10')
		) {
			setLogoutFalse();
		} else {
			setLogoutTrue();
		}
		// 发放
		if (selectedRowKeys.length === 1 && (selectedRows[0].status === '2')) {
			setFalse();
		} else {
			setTrue();
		}
		handleKeys(selectedRowKeys);
		handleRows(selectedRows)
	};
	return (
		<Fragment>
			<div className={styles.searchBar}>
				<span className={styles.title}>箱包补偿单列表</span>
				<div className={styles.option}>
					<AuthComponent authCode="luggageLndemnify.index.confirmation">
						<Button
						 disabled={disBtn}
						  onClick={confirmation}
						   type="primary"
						    icon="check">线下发放</Button>
					</AuthComponent>
					<AuthComponent authCode="luggageLndemnify.index.logout">
						<Button
						 disabled={logoutBtn}
						  onClick={logoutBtnFun}
						   type="primary"
						    icon="close">注销</Button>
					</AuthComponent>
				</div>
			</div>
			<Table
				rowSelection={
					(AuthComponent.getAuth('luggageLndemnify.index.logout') ||
						AuthComponent.getAuth('luggageLndemnify.index.confirmation'))
						? {
							// selectedRowKeys: [],
							selectedRowKeys: selectKeys,
							onChange: onSelectChange
						}
						: false
				}
				pagination={{
					showSizeChanger: true,
					showTotal: (total, range) => `${range[0]}-${range[1]} 共 ${total} 项`,
					total: compensationD.total
				}}
				className="single"
				size='small'
				rowKey="orderId"
				loading={compensationL}
				columns={columns}
				dataSource={compensationD.data}
				scroll={{ x: 1000, y: 300 }}
				onRow={record => {
					return {
						onDoubleClick: event => {
							if (AuthComponent.getAuth('luggageLndemnify.index.showDetail')) {
								let luggageLndemnifyDetailsState = {
									type: 'examine',
									orderId: record.orderId,
									status: record.status,
									selectRows: record
								};
								window.localStorage.setItem('luggageLndemnifyDetailsState', JSON.stringify(luggageLndemnifyDetailsState));
								router.push({
									pathname: '/compensation/luggageLndemnifyDetails',
									state: luggageLndemnifyDetailsState
								})
							}
						}
					}
				}}
			/>
			{/* 审核步骤 */}
			<VerifyStep sData={sData} handleVerify={handleVerify} modalVisible={verifystep} />

		</Fragment>
	)
}

export default ListOfClaims;
